import 'package:flutter/foundation.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:xws/res/app_configs.dart';

import 'log_util.dart';
import 'storage_util.dart';

/// 收到消息的回调处理
typedef OnRecive = Function(Map<String, dynamic> event);

/// 推送相关
class PU {
  PU._();

  static final JPush _jpush = JPush();

  static JPush get instance => _jpush;

  static String? _key = '';

  static bool _ready = false;

  static bool notifyPageNow = false;

  static Future<dynamic> _onReceive(Map<String, dynamic> event) async {
    if (_handleList.isNotEmpty) _handleList.last.call(event);

    onRecive?.call(event);
  }

  static OnRecive? onRecive;

  static void putHandler(OnRecive re) {
    _handleList.add(re);
  }

  static void popHandler() {
    _handleList.removeLast();
  }

  static void clearHandler() {
    onRecive = null;
    _handleList.clear();
  }

  static final List<OnRecive> _handleList = <OnRecive>[];

  ///添加处理回调
  static Future<void> setHandler({
    EventHandler? onOpenNotification,
    EventHandler? onReceiveMessage,
    EventHandler? onReceiveNotificationAuthorization,
  }) async {
    try {
      _jpush.addEventHandler(
        onReceiveNotification: _onReceive,
        onOpenNotification: onOpenNotification,
        onReceiveMessage: onReceiveMessage,
        onReceiveNotificationAuthorization: onReceiveNotificationAuthorization,
      );
    } catch (e) {
      error('添加回调失败:$e');
    }
  }

  ///获取初始化推送信息
  static Future<Map<dynamic, dynamic>?> getInitMsg() async {
    try {
      return await _jpush.getLaunchAppNotification();
    } catch (e) {
      return null;
    }
  }

  /// 设置角标
  static Future<void> setJPushBadge(int count) async {
    try {
      await _jpush.setBadge(count);
    } catch (e) {
      error('设置角标失败:$e');
    }
  }

  /// 更改推送状态
  static Future<void> setJPushEnable({bool enable = true}) async {
    try {
      enable ? await _jpush.resumePush() : await _jpush.stopPush();
    } catch (e) {
      error('更改推送状态出错:$e');
    }
  }

  /// 清除通知消息
  static Future<void> cancelJPushNotify({int id = 0, bool clearAll = false}) async {
    try {
      if (clearAll) {
        _jpush.clearAllNotifications();
        setJPushBadge(0);
      } else {
        _jpush.clearNotification(notificationId: id);
      }
    } catch (e) {
      error('清除通知消息失败:$e');
    }
  }

  /// 打印id
  static String getJPushId() {
    warning('pushid:$_key');
    return _key ?? '';
  }
}

/// 初始化极光推送
Future<void> initJpush() async {
  try {
    if (PU._ready) return;

    debug('init jpush');

    PU._jpush.setup(
      appKey: AppConfigs.jPushAppKey,
      channel: 'developer-default',
      production: !kDebugMode,
      debug: kDebugMode,
    );

    PU._jpush.applyPushAuthority(const NotificationSettingsIOS(sound: true, alert: true, badge: true));

    final String? _pushId = getV<String>('pushId');

    if (_pushId != null && _pushId.isNotEmpty) {
      PU._key = _pushId;
    } else {
      PU._key = await PU._jpush.getRegistrationID();
      setV<String>('pushId', PU._key);
    }

    PU._ready = true;
  } catch (e) {
    error('推送初始化失败:$e');
  }
}
